package org.benjamin.lending.controller;

import org.benjamin.lending.domain.BJUIData;
import org.benjamin.lending.domain.BJUIResult;
import org.benjamin.lending.domain.BasicIndex;
import org.benjamin.lending.domain.entity.BusinessInfo;
import org.benjamin.lending.service.BusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by xywen on 2017/6/2.
 */
@Controller
@RequestMapping("business")
public class BusinessController {

    @Autowired
    private BusinessService businessService;

    @RequestMapping(value = "index")
    public String index(){
        return "business/index";
    }

    @GetMapping("create")
    public String toCreate(ModelMap modelMap){
        modelMap.addAttribute("businessInfo",new BusinessInfo());
        return "business/create";
    }

    @PostMapping("create")
    public BJUIResult doCreate(BusinessInfo businessInfo, BindingResult bindingResult){
        if(!bindingResult.hasErrors()){
            this.businessService.save(businessInfo);
            return BJUIResult.defaultSuccess();
        }
        return BJUIResult.defaultFail("失败");

    }

    @ResponseBody
    @RequestMapping(value = "data.json")
    public BJUIData data(BasicIndex basicIndex){
        Page<BusinessInfo> businessInfos = this.businessService.findBusinessInfo(basicIndex.getPageRequest());
        return new BJUIData(businessInfos);
    }
}
